﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using Kelper.Domain.Models;
using Kelper.Domain.Data.Abstract;

namespace Kelper.Domain.Data
{
    public class KelperDbContext : DbContext
    {
        public DbSet<Recipe> Recipes { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Ingredient> Ingredients { get; set; }
        public DbSet<Tag> Tags { get; set; }

        public KelperDbContext()
        {
            Database.SetInitializer(new DropCreateAndSeedIfChange());
            Database.CreateIfNotExists();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Recipe>()
                .HasMany<Ingredient>(r => r.Ingredients)
                .WithMany(i => i.Recipes)
                .Map(t => t.MapLeftKey("ID").MapRightKey("Name"));

            modelBuilder.Entity<Recipe>()
                .HasMany<Tag>(r => r.Tags)
                .WithMany(i => i.Recipes)
                .Map(t => t.MapLeftKey("ID").MapRightKey("Name"));

            modelBuilder.Entity<Recipe>()
                .HasRequired<User>(r => r.Author)
                .WithMany(u => u.Recipes);

            modelBuilder.Entity<Category>()
                .HasMany<Recipe>(c => c.Recipes)
                .WithRequired(r => r.Category);

            modelBuilder.Entity<User>()
                .HasMany<Recipe>(u => u.Recipes)
                .WithRequired(r => r.Author);
        }
    }
}